layui.use(['form','table','laypage'], function(){
  var table = layui.table;
  var form = layui.form,
	layer = layui.layer;
 
 //监听select
	form.on('select(zcate)',
	function(data) {
		var params = {};
		params.id = data.value;
		$.ajax({
			type: "POST",
			url: "/admin/category/lowerCate.html",
			cache: false, //禁用缓存
			data: params, //传入组装的参数
			dataType: "json",
			success: function (result) {
				console.log(result);
				var str = '<option value="">请选择产品子分类</option>';
				if(result.code==10001){
					var i;
					var info = result.option;
					for (i in info) {
						str += '<option value="'+info[i].category_id+'">'+info[i].category_name+'</option>';
					}
					$('#cat_id').html(str);
					form.render('select');
				}else{
					$('#cat_id').html('<option value="">请选择产品子分类</option>');
					form.render('select');
				}
			},
			error:function () {
				parent.layer.msg('网络错误', {icon: 5});
			}
		})
	});
 
	/*初始化表格*/
	function tableInit(where = {})
	{  
	  table.render({
		elem: '#dataTables-example'
		,url:'/shop/addorder/ogoodslist.html'
		,where:where
		,method:'POST'
		,parseData: function(res){ //res 即为原始返回的数据
			var data_arr = [];
            //封装返回数据
			console.log(res);
			for (i in res.data) {
                if($.inArray(res.data[i].goods_id,data_gids) < 0)
                {
                    res.data[i]['reason'] = "<button class='layui-btn purchase' gid='"+res.data[i].goods_id+"'>缺货采购</button>";
                    data_arr.push(res.data[i]);
                }
			}
            if(data_arr.length == 0)
            {
                var arr = [];
                arr.goods_id = '';
                arr.goods_sn = '';
                arr.goods_name = '';
                arr.category_id = '';
                arr.cat_id = '';
                arr.brand_name = '';
                arr.marker = '';
                arr.memory_name = '';
                arr.attribute_name = '';
                arr.colour_name = '';
                arr.gnumber = '';
                arr.unit = '';
                arr.selling_price = '';
                arr.trade_price = '';
                arr.reason = '';
                data_arr.push(arr);  
            }
			return {
			  "code": 10001, //解析接口状态
			  "msg": '', //解析提示文本
			  "count": res.total, //解析数据长度
			  "data": data_arr //解析数据列表
			};
		}
		,cols: [[
		  {field:'goods_id', title: '序号'}
          ,{field:'goods_sn', title: '产品编码'}
		  ,{field:'goods_name', title: '产品名称'}
		  ,{field:'category_id', title: '产品分类'}
		  ,{field:'cat_id', title: '产品子分类'}
		  ,{field:'brand_name', title: '品牌'}
		  ,{field:'marker', title: '型号'}
		  ,{field:'memory_name', title: '内存'}
		  ,{field:'attribute_name', title: '属性'}
		  ,{field:'colour_name', title: '颜色'}
		  ,{field:'gnumber', title: '剩余数量'}
		  ,{field:'unit', title: '单位'}
		  ,{field:'selling_price', title: '零售单价（元）'}
		  ,{field:'trade_price', title: '批发价（元）'}
          ,{field:'reason', title: '操作'}
		]]
		,page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
		  layout: ['prev', 'page', 'next', 'skip', 'count']
		}
		,response: {
			statusCode: 10001
		}
        ,done: function(res, curr, count){
             $('#data-tr').find('.layui-table-body').find("table" ).find("tbody").children("tr").on('dblclick',function(){
               var info = res.data[$(this).data('index')];
               $(this).remove();
               selection([info])
               })
        }
	  });
	}
	tableInit();
    
    var data_selection = [];
    var data_gids = [];
    function selection(info = [])
    {
        if(info != [])
        {
            for (i in info)
            {
                info[i]['reason'] = "<button class='layui-btn selection-cancel' gid='"+info[i]['goods_id']+"'>取 消</button>";
                data_selection.push(info[i]);
                data_gids.push(info[i].goods_id);
            }
        }
        //展示已知数据
          table.render({
            elem: '#dataTables-selection'
            ,cols: [[ //标题栏
              {field:'goods_id', title: '序号'}
              ,{field:'goods_sn', title: '产品编码'}
              ,{field:'goods_name', title: '产品名称'}
              ,{field:'category_id', title: '产品分类'}
              ,{field:'cat_id', title: '产品子分类'}
              ,{field:'brand_name', title: '品牌'}
              ,{field:'marker', title: '型号'}
              ,{field:'memory_name', title: '内存'}
              ,{field:'attribute_name', title: '属性'}
              ,{field:'colour_name', title: '颜色'}
              ,{field:'gnumber', title: '剩余数量'}
              ,{field:'unit', title: '单位'}
              ,{field:'selling_price', title: '零售单价（元）'}
              ,{field:'trade_price', title: '批发价（元）'}
              ,{field:'reason', title: '操作'}
            ]]
            ,data: data_selection
            //,skin: 'line' //表格风格
            //,even: true
            //,page: true //是否显示分页
            //,limits: [5, 7, 10]
            //,limit: 5 //每页默认显示的数量
          });
    }
    
    console.log(parent.open_data());
    
    $('body').on('click', '.selection-cancel', function(){
        var gid = $(this).attr('gid');
        var data_sel = [];
        var data_gid = [];
        var gids = '';
        for (i in data_selection) {
                if(data_selection[i]['goods_id'] != gid)
                {
                    data_sel.push(data_selection[i]);
                    data_gid.push(data_selection[i]['goods_id']);
                    gids += data_selection[i]['goods_id'] + ',';
                }
			}
         gids = gids.substr(0, gids.length - 1);
         data_selection = data_sel;
         data_gids = data_gid;
		$(this).closest('tr').remove();
        tableInit({gids:gids});
	});
    $('body').on('click', '.purchase', function(){
		var get_this = $(this);
		parent.layer.confirm('你确定要采购该商品吗?', function(){
			var params = {};
			params.id = get_this.attr('gid');
			$.ajax({
				type: "POST",
				url: '/shop/addorder/setpurchase',
				cache: false, //禁用缓存
				data: params, //传入组装的参数
				dataType: "json",
				success: function (result) {
					if(result.code==10001){
						parent.layer.msg('操作成功', {icon: 1});
					}else{
						parent.layer.msg(result.msg, {icon: 5});
					}
				},
				error:function () {
					parent.layer.msg('网络错误', {icon: 5});
				}
			})
		});
	});
	//监听提交
	form.on('submit(sreach)',
	function(data) {
		tableInit(data.field);
		return false;
	});
    /*关闭页面*/
    form.on('submit(close)',
    function(data) {
        //关闭当前frame
        xadmin.close();
        return false;
    });
    /*确定选中商品*/
    form.on('submit(sure)',
    function(data) {
        //console.log(data_selection);
        parent.GetValue(data_selection);
        //关闭当前frame
        xadmin.close();
        return false;
    });
});

